package imageviewer.beans;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import imageviewer.persistence.Database;
import imageviewer.domain.PicData;


public class PicBean extends BasicBean  {

	PicData pic = null;
	
	Long id = null; 
    

	public PicData getPic() {
		return pic;
	}


	public void setPic(PicData pic) {
		this.pic = pic;
	}


	public void fetchPic() {
		try {
			Connection con = Database.getConnection();
			
			Statement stmt = con.createStatement();
			
			if (null == id)
				pic = null;		
			else {
				ResultSet rs = stmt
						.executeQuery("SELECT pd.pic FROM Pic_Data pd, Picture p WHERE p.Pic_Data_Id = pd.Pic_Data_Id AND p.Pic_Id="
								+ id.longValue());
				while (rs.next()) {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					int readBytes = 0;
					String path = rs.getString(1);
					FileInputStream is = new FileInputStream(path);
					do {
						readBytes = is.read();
						out.write(readBytes);
					} while (readBytes >= 0);
					pic = new PicData(out.toByteArray());
					pic.setId(id);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	public Long getId() {
		return id;
	}


	public void setId(Long id) {
		this.id = id;
	}

}
